﻿using System.IO;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.Extensions.Logging;
using Swashbuckle.AspNetCore.Swagger;
using NLog.Web;
using NLog.Extensions.Logging;

using Read.Web.Admin;
using System.Text;

namespace Read.Web
{
    /// <summary>
    /// Startup
    /// </summary>
    public class Startup
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="configuration"></param>
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            Services.GlobalService.Configuration = Configuration;
        }

        /// <summary>
        /// IConfiguration
        /// </summary>
        /// <returns></returns>
        public IConfiguration Configuration
        {
            get;
        }

        /// <summary>
        /// ConfigureServices
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddSession();
            services.AddMvc(
            //这里是不允许匿名访问
            // options =>
            // {
            //     var policy = new AuthorizationPolicyBuilder()
            //                     .RequireAuthenticatedUser()
            //                     .Build();
            //     options.Filters.Add(new AuthorizeFilter(policy));
            // }
            )
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new JSONStringContractResolver());
            #region CORS
            //获取配置文件
            //var urls = Configuration["AppConfig:Cores"].Split(',');
            services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigin",
                //指定域
                //builder => builder.WithOrigins("http://localhost:5001").AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod());
                builder => builder.WithOrigins().AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod());
            });
            #endregion
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            }).AddCookie(
            //用自定义的权限机制,这里暂时不用
            // options =>
            // {
            //     options.LoginPath = new PathString("/Account/Login");
            //     options.LogoutPath = new PathString("/Account/Logout");
            //     options.AccessDeniedPath = new PathString("/Account/AccessDenied");
            //     //options.Cookie.Path = "/";
            // }
            );

            //获取配置方法(在控制器中获取)
            //services.AddOptions().Configure<ConnectionStringsModel>(Configuration.GetSection("ConnectionStrings"));

            //Swagger生成文档信息
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Title = "API接口",
                    Version = "1.0.0",
                    Description = "REST API接口文档",
                    Contact = new Contact()
                    {
                        Name = "Hei幕"
                    },
                    License = new License
                    {
                        Name = "Apache 2.0",
                        Url = "http://www.apache.org/licenses/LICENSE-2.0.html"
                    }
                });

                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                c.IncludeXmlComments(Path.Combine(basePath, "Read.Web.xml"));
                c.IncludeXmlComments(Path.Combine(basePath, "Read.Models.xml"));
            });
        }

        /// <summary>
        /// Configure
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        /// <param name="loggerFactory"></param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                //这是为了防止中文乱码
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                /* NLog */
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                env.ConfigureNLog(Path.Combine(basePath, "nlog.config"));
                //loggerFactory.AddConsole(Configuration.GetSection("Logging"));
                //loggerFactory.AddDebug();
                loggerFactory.AddNLog();
                app.AddNLogWeb();
                /* NLog */
                app.UseExceptionHandler("/Base/Error");
            }

            //静态文件
            app.UseStaticFiles();
            //跨域
            app.UseCors("AllowSpecificOrigin");

            //错误页面
            // app.UseExceptionHandler("/errors/500");
            // app.UseStatusCodePagesWithReExecute("/errors/{0}");

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
                c.ShowRequestHeaders();
            });

            // 使用Authentication中间件,这里关于认证只有一个中间件，具体的认证策略将在服务中注册
            app.UseAuthentication();

            //Session 会报错
            app.UseSession();
            // 取值：string a=HttpContext.Session.GetString("KEY");
            // 赋值：HttpContext.Session.SetString(KEY，value);

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                //区域
                //http://www.cnblogs.com/dotNETCoreSG/p/aspnetcore-4_4_6-areas.html
                //http://www.bubuko.com/infodetail-1819311.html
                //http://www.bkjia.com/Asp_Netjc/1150314.html
                //return RedirectToAction("index", "home", new { Area = "Admin" });
                //<a asp-area="Admin" asp-controller="home" asp-action="index">Test</a>
                routes.MapRoute(
                    name: "adminarea",
                    template: "{area:exists}/{controller=Home}/{action=Index}/{id?}",
                    defaults: new { });
            });
        }

        /// <summary>
        /// 解决JOSN大小写问题
        /// </summary>
        public class JSONStringContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
        {
            /// <summary>
            /// ResolvePropertyName
            /// </summary>
            /// <param name="propertyName"></param>
            /// <returns></returns>
            protected override string ResolvePropertyName(string propertyName)
            {
                return propertyName;
            }
        }
    }
}
